package com.shangxia.monomer.study.designPatterns.behavioralType.observer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: monomer
 * @ClassName: ObserverDemo
 * @Time: 2021/7/27
 * @Author: zhouy
 * @Description:
 * @Experience:
 */

@Slf4j
public class ObserverDemo {
    /**
     * ObserverAble
     * ApplicationListener
     */

    public static void main(String[] args) {
        Subject subject = new Subject();
        Observer task1 = new task1();
        Observer task2 = new task2();
        subject.addObserver(task1);
        subject.addObserver(task2);
        subject.notifyAllObserver("hello world");
        subject.removeObserver(task1);
        subject.notifyAllObserver("ni hao");
    }
}

class Subject {
    private List<Observer> container = new ArrayList<>();

    public void addObserver(Observer observer) {
        container.add(observer);
    }

    public void removeObserver(Observer observer) {
        container.remove(observer);
    }

    public void notifyAllObserver(Object obj) {
        for (Observer observer : container) {
            observer.update(obj);
        }
    }
}

interface Observer {
    void update(Object obj);
}

class task1 implements Observer {

    @Override
    public void update(Object obj) {
        System.out.println("task1  " + obj.toString());
    }
}

class task2 implements Observer {

    @Override
    public void update(Object obj) {
        System.out.println("task2  " + obj.toString());
    }
}